package com.yangyang.rpc.core.netcom.netty.client;

import com.yangyang.rpc.core.serialize.Serializer;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * Created by chenshunyang on 2016/11/22.
 */
public class NettyClientPoolFactory extends BasePooledObjectFactory<NettyClientPoolProxy>{

    private String host;
    private int port;
    private Serializer serializer;


    public NettyClientPoolFactory(String host, int port, Serializer serializer) {
        this.host = host;
        this.port = port;
        this.serializer = serializer;
    }

    @Override
    public NettyClientPoolProxy create() throws Exception {
        NettyClientPoolProxy nettyClientProxy = new NettyClientPoolProxy();
        nettyClientProxy.createProxy(host,port,serializer);
        return nettyClientProxy;
    }

    @Override
    public PooledObject<NettyClientPoolProxy> wrap(NettyClientPoolProxy obj) {
        return new DefaultPooledObject<NettyClientPoolProxy>(obj);
    }

    @Override
    public void destroyObject(PooledObject<NettyClientPoolProxy> p)
            throws Exception {
        NettyClientPoolProxy nettyClientProxy = p.getObject();
        nettyClientProxy.close();
    }

    @Override
    public boolean validateObject(PooledObject<NettyClientPoolProxy> p) {
        NettyClientPoolProxy nettyClientProxy = p.getObject();
        return nettyClientProxy.isValidate();
    }
}
